<template>
  <div class="order-submission">
    <div class="line">
      <img src="@assets/images/line.jpg" />
    </div>
    <div class="address acea-row row-between-wrapper" @click="addressTap">
      <div class="addressCon" v-if="addressInfo.name">
        <div class="name">
          {{ addressInfo.name }}
          <span class="phone">{{ addressInfo.phoneNumber }}</span>
        </div>
        <div>
          <span
            class="default font-color-red"
            v-if="addressInfo.defaultStatus == 1"
            >[默认]</span
          >
          {{ addressInfo.province }}{{ addressInfo.city }}{{ addressInfo.region
          }}{{ addressInfo.detailAddress }}
        </div>
      </div>
      <div class="addressCon" v-else>
        <div class="setaddress">设置收货地址</div>
      </div>
      <div class="iconfont icon-jiantou"></div>
    </div>

    <div
      v-for="item1 in confirmOrderResultList"
      :key="item1.id"
      v-if="
        item1.cartPromotionItemList && item1.cartPromotionItemList.length > 0
      "
    >
      <div class="orderGoods">
        <div class="total font-color-red">
          共{{ item1.cartPromotionItemList.length }}件商品,店铺 【{{
            item1.storeName
          }}】
        </div>
        <div class="goodWrapper">
          <div
            class="item acea-row row-between-wrapper"
            v-for="cart in item1.cartPromotionItemList"
            :key="cart.id"
          >
            <div class="pictrue">
              <img :src="cart.productPic" class="image" />
            </div>
            <div class="text">
              <div class="acea-row row-between-wrapper">
                <div class="name line1">{{ cart.productName }}</div>
                <div class="num">x {{ cart.quantity }}</div>
              </div>
              <div class="attr line1" v-if="cart.productAttr">
                {{ cart.productAttr }}
              </div>
              <div class="money font-color-red">￥{{ cart.price }}</div>
            </div>
          </div>
        </div>
        <div class="moneyList">
          <div
            class="item acea-row row-between-wrapper"
            v-if="item1.calcAmount.totalAmount !== undefined"
          >
            <div>商品总价：</div>
            <div class="money">￥{{ item1.calcAmount.totalAmount }}</div>
          </div>
          <div
            class="item acea-row row-between-wrapper"
            v-if="item1.calcAmount.freightAmount > 0"
          >
            <div>运费：</div>
            <div class="money">￥{{ item1.calcAmount.freightAmount }}</div>
          </div>

          <div
            class="item acea-row row-between-wrapper"
            v-if="item1.calcAmount.promotionAmount > 0"
          >
            <div>优惠金额：</div>
            <div class="money">-￥{{ item1.calcAmount.promotionAmount }}</div>
          </div>
          <div
            class="item acea-row row-between-wrapper"
            v-if="item1.calcAmount.payAmount > 0"
          >
            <div>支付金额：</div>
            <div class="money">￥{{ item1.calcAmount.payAmount }}</div>
          </div>
          <!-- <div
            class="item acea-row row-between-wrapper"
            v-if="memberIntegration > 0"
          >
            <div>积分抵扣：</div>
            <div class="money">-￥{{ memberIntegration }}</div>
          </div>-->
        </div>
      </div>
    </div>

    <div
      class="orderGoods"
      v-for="item1 in basicGiftsList"
      v-if="item1.giftsList && item1.giftsList.length > 0"
    >
      <div class="total">{{ item1.name }}</div>
      <div class="goodWrapper">
        <div
          class="item acea-row row-between-wrapper"
          v-for="(item, index) in item1.giftsList"
          :key="index"
        >
          <div class="pictrue">
            <img :src="item.pic" class="image" />
          </div>
          <div class="text">
            <div class="acea-row row-between-wrapper">
              <div class="name line1">{{ item.name }}</div>
            </div>
            <div class="attr line1" v-if="item.rule">
              {{ item.price }}
            </div>
            <div class="money font-color-red">￥{{ item.price }}</div>
          </div>
        </div>
      </div>
    </div>

    <div class="wrapper">
      <div class="item">
        <div>备注信息</div>
        <textarea
          placeholder="请添加备注（150字以内）"
          v-model="desc"
        ></textarea>
      </div>
    </div>
    <div class="wrapper">
      <div class="item">
        <div>支付方式</div>
        <div class="list">
          <div
            class="payItem acea-row row-middle"
            :class="active === 'weixin' ? 'on' : ''"
            @click="payItem('weixin')"
            v-show="isWeixin"
          >
            <div class="name acea-row row-center-wrapper">
              <div
                class="iconfont icon-weixin2"
                :class="active === 'weixin' ? 'bounceIn' : ''"
              ></div>
              微信支付
            </div>
            <div class="tip">微信快捷支付</div>
          </div>
          <div
            class="payItem acea-row row-middle"
            :class="active === 'weixin' ? 'on' : ''"
            @click="payItem('weixin')"
            v-show="!isWeixin"
          >
            <div class="name acea-row row-center-wrapper">
              <div
                class="iconfont icon-weixin2"
                :class="active === 'weixin' ? 'bounceIn' : ''"
              ></div>
              微信支付
            </div>
            <div class="tip">微信快捷支付</div>
          </div>
          <div
            class="payItem acea-row row-middle"
            :class="active === 'yue' ? 'on' : ''"
            @click="payItem('yue')"
          >
            <div class="name acea-row row-center-wrapper">
              <div
                class="iconfont icon-icon-test"
                :class="active === 'yue' ? 'bounceIn' : ''"
              ></div>
              余额支付
            </div>
            <div class="tip">可用余额：{{ blance || 0 }}</div>
          </div>
          <div
            class="payItem acea-row row-middle"
            :class="active === 'offline' ? 'on' : ''"
            @click="payItem('offline')"
            v-if="offlinePayStatus === 1 && deduction === false"
          >
            <div class="name acea-row row-center-wrapper">
              <div
                class="iconfont icon-yinhangqia"
                :class="active === 'offline' ? 'bounceIn' : ''"
              ></div>
              线下支付
            </div>
            <div class="tip">线下方便支付</div>
          </div>
        </div>
      </div>
    </div>

    <div style="height:1.2rem"></div>
    <div class="footer acea-row row-between-wrapper">
      <div>
        合计:
        <span class="font-color-red">￥{{ totalPayAmount }}</span>
      </div>
      <div class="settlement" @click="createOrder">立即结算</div>
    </div>
    <CouponListWindow
      v-on:couponchange="changecoupon($event)"
      v-model="showCoupon"
      :checked="coupon.id"
      :couponList="usableCoupon"
      @checked="changeCoupon"
    ></CouponListWindow>
    <AddressWindow
      @checked="changeAddress"
      @redirect="addressRedirect"
      v-model="showAddress"
      :checked="addressInfo.id"
      ref="mychild"
    ></AddressWindow>
  </div>
</template>
<script>
import OrderGoods from "@components/OrderGoods";
import CouponListWindow from "@components/CouponListWindow";
import AddressWindow from "@components/AddressWindow";
import {
  postOrderConfirmStore,
  createOrder,
  balancePay,
  addGroup,
  preGroupActivityOrder
} from "@api/order";
import { mapGetters } from "vuex";
import { pay } from "@libs/wechat";
import { isWeixin } from "@utils";

const NAME = "OrderSubmission",
  _isWeixin = isWeixin();
export default {
  name: NAME,
  components: {
    OrderGoods,
    CouponListWindow,
    AddressWindow
  },
  props: {},
  data: function() {
    return {
      desc: "", //备注
      memberIntegration: 0,
      blance: 0,
      totalPayAmount: 0,
      payType: 1, //1微信 2支付宝
      type: 1,
      groupType: "",
      groupActivityId: "",
      basicGiftsVar: "",
      skillId: 0,
      goodsId: 0,
      mgId: 1,
      cartId: "",
      cartIds: "",
      addressId: "",
      couponId: "",
      memberCouponId: "",
      coupon: {
        amount: 0
      },
      groupActivity: null,
      memberReceiveAddressList: [],
      basicGiftsList: [],
      confirmOrderResultList: [],
      cartPromotionItemList: [],
      calcAmount: {
        totalAmount: 0,
        freightAmount: 0,
        promotionAmount: 0,
        payAmount: 0
      },
      couponList: [],
      addressData: {
        name: null,
        phoneNumber: "",
        detailAddress: "",
        region: ""
      },
      offlinePayStatus: 2,
      from: _isWeixin ? "weixin" : "weixinh5",
      deduction: false,
      isWeixin: _isWeixin,
      pinkId: 0,
      active: _isWeixin ? "weixin" : "yue",
      showCoupon: false,
      showAddress: false,
      addressInfo: {},

      orderGroupInfo: {
        priceGroup: {}
      },
      usableCoupon: {},
      addressLoaded: false,
      useIntegral: false,
      orderPrice: {
        pay_price: "计算中"
      },
      mark: ""
    };
  },
  computed: mapGetters(["userInfo"]),
  watch: {
    useIntegral() {
      //  this.computedPrice();
    },
    $route(n) {
      if (n.name === NAME) this.getCartInfo();
    }
  },
  mounted: function() {
    var that = this;
    this.getCartInfo();
    if (that.$route.query.pinkid !== undefined)
      that.pinkId = that.$route.query.pinkid;
  },
  methods: {
    computedPrice(data) {
      console.log(data);

      if (!data) {
        this.$dialog.error("请不要重复创建订单!");
        return this.$router.go(-1);
      }

      this.blance = data.blance;
      this.totalPayAmount = data.totalPayAmount;
      this.usableCoupon = data.couponHistoryDetailList || {};
      if (this.usableCoupon && this.usableCoupon.length > 0) {
        this.coupon = this.usableCoupon[0];
        this.couponId = this.coupon.coupon.id;
        this.memberCouponId = this.coupon.id;
      }
      this.addressInfo = data.address || {};

      this.confirmOrderResultList = data.confirmOrderResultList;
      this.calcAmount = data.calcAmount;
      if (this.addressData) {
        this.addressId = this.addressData.id;
      }
      this.memberReceiveAddressList = data.memberReceiveAddressListaddress;
    },

    getCartInfo() {
      let data;
      this.type = this.$route.query.type;

      console.log("type=" + this.type);
      if (this.$route.query.groupActivityId) {
        // 团购
        let params = { groupId: this.$route.query.groupActivityId };

        preGroupActivityOrder(params)
          .then(res => {
            this.offlinePayStatus = 1;
            this.deduction = res.data.deduction;
            this.computedPrice(res.data);
          })
          .catch(() => {
            this.$dialog.error("加载订单数据失败");
          });
        this.groupActivityId = this.$route.query.groupActivityId;
        this.groupActivity = data.groupActivity;
      } else {
        if (this.$route.query.groupType) {
          // 拼团
          this.groupType = this.$route.query.groupType;
          this.goodsId = this.$route.query.id;
          this.mgId = this.$route.query.mgid;

          if (this.$route.query.skuId) {
            let params = {
              groupId: this.$route.query.groupId,
              goodsId: this.$route.query.id,
              skuId: this.$route.query.skuId
            };
            addGroup(params)
              .then(res => {
                this.offlinePayStatus = 1;
                this.deduction = res.data.deduction;
                this.computedPrice(res.data);
              })
              .catch(() => {
                this.$dialog.error("加载订单数据失败");
              });
          } else {
            let params = {
              groupId: this.$route.query.groupId,
              goodsId: this.$route.query.id
            };
            addGroup(params)
              .then(res => {
                this.offlinePayStatus = 1;
                this.deduction = res.data.deduction;
                this.computedPrice(res.data);
              })
              .catch(() => {
                this.$dialog.error("加载订单数据失败");
              });
          }
        } else {
          if (this.$route.query.type == 1) {
            // 详情
            this.cartId = this.$route.query.id;
            let params = {
              cartId: this.$route.query.id,
              type: this.$route.query.type
            };
            postOrderConfirmStore(params)
              .then(res => {
                this.offlinePayStatus = 1;
                this.deduction = true;
                this.computedPrice(res.data);
              })
              .catch(error => {
                console.log(error);
              });
          } else if (this.$route.query.type == 2) {
            // 购物车
            let params = {
              cartIds: this.$route.query.cartIds,
              type: this.$route.query.type
            };
            postOrderConfirmStore(params)
              .then(res => {
                this.offlinePayStatus = 1;
                this.deduction = true;
                this.computedPrice(res.data);
              })
              .catch(() => {
                this.$dialog.error("加载订单数据失败");
              });
            this.cartIds = this.$route.query.cartIds;
          } else if (this.$route.query.type == 6) {
            // 秒杀
            let params = {
              skillId: this.$route.query.skillId,
              type: this.$route.query.type
            };
            postOrderConfirmStore(params)
              .then(res => {
                this.offlinePayStatus = 1;
                this.deduction = true;
                this.computedPrice(res.data);
              })
              .catch(() => {
                this.$dialog.error("加载订单数据失败");
              });
            this.skillId = this.$route.query.skillId;
          }
        }
      }
    },
    addressTap: function() {
      this.showAddress = true;
      if (!this.addressLoaded) {
        this.addressLoaded = true;
        this.$refs.mychild.getAddressList();
      }
    },
    addressRedirect() {
      this.addressLoaded = false;
      this.showAddress = false;
    },
    couponTap: function() {
      this.showCoupon = true;
    },
    changeCoupon: function(coupon) {
      if (!coupon) {
        let coupons = { name: "不使用优惠券", id: 0, amount: 0 };
        this.coupon = { name: "不使用优惠券", id: 0, coupon: coupons };
      } else {
        this.coupon = coupon;
      }
      console.log(this.coupon);
      this.couponId = this.coupon.coupon.id;
      this.memberCouponId = this.coupon.id;

      //  this.computedPrice();
    },
    payItem: function(index) {
      this.active = index;
    },
    changeAddress(addressInfo) {
      this.addressInfo = addressInfo;
    },
    createOrder() {
      if (!this.active) return this.$dialog.toast({ mes: "请选择支付方式" });
      if (!this.addressInfo.id)
        return this.$dialog.toast({ mes: "请选择收货地址" });
      this.$dialog.loading.open("生成订单中");
      this.addressId = this.addressInfo.id;
      // 拼团
      if (this.groupType) {
        if (!this.mgId) {
          this.mgId = 1;
        }

        //   data = await Api.apiCall('post', Api.order.acceptGroup, params);
      } else {
        let params = null;
        // detail
        if (this.type == 1) {
          params = {
            basicGiftsVar: this.basicGiftsVar,
            orderType: 1,
            type: 1,
            cartId: this.cartId,
            addressId: this.addressId,
            couponId: this.couponId,
            memberCouponId: this.memberCouponId,
            content: this.desc
          };
          if (this.groupActivityId) {
            params = {
              groupActivityId: this.groupActivityId,
              orderType: 3,
              type: 1,
              cartId: this.cartId,
              addressId: this.addressId,
              couponId: this.couponId,
              memberCouponId: this.memberCouponId,
              content: this.desc
            };
          }
        }
        // 购物车
        if (this.type == 2) {
          params = {
            orderType: 1,
            type: 2,
            cartIds: this.cartIds,
            addressId: this.addressId,
            couponId: this.couponId,
            content: this.desc
          };
        }

        // 秒杀
        if (this.type == 6) {
          params = {
            type: 6,
            skillId: this.skillId,
            addressId: this.addressId,
            couponId: this.couponId,
            content: this.desc,
            orderType: 6
          };
        }
        createOrder(params)
          .then(res => {
            this.$dialog.loading.close();
            const data = res.data.order;
            console.log(data.status);
            switch (data.status) {
              case "ORDER_EXIST":
              case "EXTEND_ORDER":
              case "PAY_DEFICIENCY":
              case 12:
                this.$dialog.toast({ mes: res.msg });
                if (this.active == "yue") {
                  let params1 = {
                    payAmount: data.payAmount,
                    balance: this.blance,
                    orderId: data.id
                  };
                  balancePay(params1)
                    .then(res => {
                      this.$router.replace({
                        path: "/order/detail/" + res.data.id
                      });
                    })
                    .catch(err => {
                      this.$dialog.error(err.msg);
                    });
                }

                break;
              case "SUCCESS":
                this.$dialog.success(res.msg);
                this.$router.replace({
                  path: "/order/detail/" + data.result.orderId
                });
                break;
              case "WECHAT_H5_PAY":
                this.$router.replace({
                  path: "/order/detail/" + data.result.orderId
                });
                setTimeout(() => {
                  location.href = data.result.jsConfig.mweb_url;
                }, 100);
                break;
              case "WECHAT_PAY":
                pay(data.result.jsConfig).finally(() => {
                  this.$router.replace({
                    path: "/order/detail/" + data.result.orderId
                  });
                });
            }
          })
          .catch(err => {
            console.log(err);
            this.$dialog.loading.close();
            this.$dialog.error(err.msg || "创建订单失败");
          });
      }
    }
  }
};
</script>
